<?php
defined("IN_IA") or exit("Access Denied");

class yzzc_sunModuleWxapp extends WeModuleStore
{
    function return_msg($code = 1, $data = array(), $msg = "success")
    {
        $res["code"] = $code;
        $res["data"] = $data;
        $res["msg"] = $msg;
        exit(json_encode($res));
    }

    function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    function getSign($appid, $msectime)
    {
        $appSecurity = 'Ej3kBb15sBFoEfKoMIj2m8DbWGASN6WP';
        return md5($appid . '&' . $msectime . '&' . $appSecurity);
    }

    /**
     * @param $url
     * @param $data
     * @return array
     * 请求API
     */
    function sendPostRequestWithStatusCode($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 设置请求头
        $headers = [
            'Content-Type: application/x-www-form-urlencoded; charset=UTF-8', // 可根据需要设置其他头信息
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'cURL请求错误: ' . curl_error($ch);
        }

        // 获取HTTP状态码
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        // 对返回数据进行JSON解析
        $responseData = json_decode($response, true);

        return ['statusCode' => $statusCode, 'data' => $responseData];
    }

    function scoreAct($uid, $type = 1, $score = 0)
    {
        global $_W;
        $data["uniacid"] = $_W["uniacid"];
        $data["uid"] = $uid;
        $data["type"] = $type;
        $data["score"] = $score;
        $data["createtime"] = time();
        pdo_insert("yzzc_sun_integral_log", $data);
        if ($score > 0) {
            pdo_update("yzzc_sun_user", array("all_integral +=" => $data["score"]), array("id" => $data["uid"]));
        }
        pdo_update("yzzc_sun_user", array("now_integral +=" => $data["score"]), array("id" => $data["uid"]));
    }

    public function wxPay($options = array())
    {
        $data["appid"] = $options["appid"];
        $data["mch_id"] = $options["mch_id"];
        $data["openid"] = $options["openid"];
        $data["nonce_str"] = $this->randstr();
        $data["body"] = $options["body"];
        $data["attach"] = $options["attach"];
        $data["out_trade_no"] = $options["out_trade_no"];
        $data["notify_url"] = $options["notify_url"];
        $data["total_fee"] = $options["total_fee"] * 100;
        $data["spbill_create_ip"] = $_SERVER["REMOTE_ADDR"];
        $data["trade_type"] = "JSAPI";
        $data["time_start"] = $options["time_start"];
        $data["time_expire"] = $options["time_expire"];
        ksort($data, SORT_STRING);
        $string = '';
        foreach ($data as $key => $v) {
            if (!empty($v)) {
                $string .= "{$key}={$v}&";
            } else {
            }
        }
        $string .= "key=" . $options["pay_key"] . '';
        $data["sign"] = strtoupper(md5($string));
        $xmlData = array2xml($data);
        $response = $this->https_request("https://api.mch.weixin.qq.com/pay/unifiedorder", $xmlData);
        $result = json_decode(json_encode(simplexml_load_string($response, "SimpleXMLElement", LIBXML_NOCDATA)), true);
        if ($result["return_code"] == "SUCCESS") {
            $payData["appId"] = $data["appid"];
            $payData["timeStamp"] = (string)time();
            $payData["nonceStr"] = $this->randstr();
            $payData["package"] = "prepay_id=" . $result["prepay_id"];
            $payData["signType"] = "MD5";
            $payString = '';
            ksort($payData, SORT_STRING);
            foreach ($payData as $key => $v) {
                $payString .= "{$key}={$v}&";
            }
            $payString .= "key=" . $options["pay_key"] . '';
            $payData["paySign"] = strtoupper(md5($payString));
            $payData["return_code"] = $result["return_code"];
        } else {
            $payData["return_code"] = $result["return_code"];
            $payData["return_msg"] = $result["return_msg"];
        }
        return $payData;
    }



    /**
     * @return void
     * 商家入驻配置
     */
    public function doPageStoreConfig(){
        global $_W,$_GPC;
        $store_config = pdo_get('yzzc_sun_store_config',['uniacid'=>$_W['uniacid']]);
        $this->return_msg(1, $store_config, '获取成功');
    }
    /**
     * @return void
     * 商家入驻审核
     */
    public function doPageStoreApply(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }
        if (empty($_GPC['name']) || empty($_GPC['mobile'])){
            $this->return_msg(-1, [], '资料不完善');
        }
        if (!pdo_get('yzzc_sun_user',['id'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']])){
            $this->return_msg(-1, [], '会员尚未注册');
        }

        $store_config = pdo_get('yzzc_sun_store_config',['uniacid'=>$_W['uniacid']]);
        if ($store_config['is_open_apply'] != 1){
            $this->return_msg(-1, [], '平台未开启商家入驻申请');
        }

        $user_drive = pdo_get('yzzc_sun_user_drive',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);
        if (!$user_drive){
            $this->return_msg(-1, [], '请先完成实名认证');
        }

        $data = [
            'uniacid'=>$_W['uniacid'],
            'uid' => trim($_GPC['uid']),
            'name' => trim($_GPC['name']),
            'mobile' => trim($_GPC['mobile']),
            'province' => trim($_GPC['province']),
            'city' => trim($_GPC['city']),
            'area' => trim($_GPC['name']),
            'createtime' => time(),
        ];

        $store = pdo_get('yzzc_sun_store',['uid'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']]);
        if ($store){
            $this->return_msg(-1, [], '请勿重复申请');
        }

        $result = pdo_insert('yzzc_sun_store',$data);
        if ($result){
            $this->return_msg(1, [], '申请成功，等待审核');
        }
        $this->return_msg(-1, [], '申请失败，请联系管理员');
    }

    /**
     * @return void
     * 创建入驻费用订单
     */
    public function doPageCreateStoreOrder(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }

        $store_config = pdo_get('yzzc_sun_store_config',['uniacid'=>$_W['uniacid']]);
        if ($store_config['is_fee'] != 1){
            $this->return_msg(-1, [], '入驻无需支付入驻费用');
        }
        $store = pdo_get('yzzc_sun_store',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);
        if ($store['status'] !=1){
            $this->return_msg(-1, [], '入驻审核未通过');
        }

        $store_order = pdo_get('yzzc_sun_store_order',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);
        if ($store_order){
            $this->return_msg(-1, [], '入驻订单已创建');
        }

        $user = pdo_get('yzzc_sun_user',['id'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']]);
        if (!$user){
            $this->return_msg(-1, [], '会员尚未注册');
        }

        $data = [
            'uid' => $_GPC['uid'],
            'order_no' => $this->getOrderNo(),
            'uniacid' => $_W['uniacid'],
            'name' => $store['name'],
            'mobile' => $store['mobile'],
            'amount' => $store_config['amount'],
            'createtime' => time()
        ];

        pdo_insert('yzzc_sun_store_order',$data);
        $oid = pdo_insertid();
        if ($oid){
            $this->return_msg(1, $oid, '创建成功');
        }
        $this->return_msg(-1, [], '创建失败，请联系管理员');
    }

    /**
     * @return void
     * 入驻商家订单支付
     */
    public function doPagePayStoreOrder()
    {
        include_once "wxpay.php";
        global $_GPC, $_W;
        $oid = intval($_GPC["oid"]);
        $out_trade_no = rand(10000, 99999) . time() . rand(10000, 99999) . $oid;
        $order_info = pdo_get("yzzc_sun_store_order", array("order_id" => $oid, "uniacid" => $_W["uniacid"]), array("amount"));
        if (!$order_info){
            $this->return_msg(-1, [],'订单不存在');
        }
        if ($order_info['status'] == 1){
            $this->return_msg(-1, [],'订单已支付');
        }

        pdo_update("yzzc_sun_store_order", array("out_trade_no" => $out_trade_no), array("order_id" => $oid));

        $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
        $appid = $appData["appid"];
        $mch_id = $appData["mchid"];
        $key = $appData["wxkey"];
        $openid = $_GPC["openid"];
        $total_fee = $order_info["amount"] * 100;

        $body = "商家入驻订单支付";
        $notify_url = $_W["siteroot"] . "addons/yzzc_sun/notify.php";

        //3 支付商家入驻订单
        $attach = $_W["uniacid"] . "@@@2@@@" . $oid;
        $wxpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $attach, $notify_url);

        $ret = $wxpay->pay();
        $this->return_msg(1, $ret);
    }

}